<template>
  <div class="login">
    <div class="box">
      <div class="icon"><img src="/static/images/M.png" alt=""></div>
      <span>使用账号 登录官网</span>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="user">
          <el-input type="text" v-model="ruleForm.user" autocomplete="off" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {getStore, removeStore, setStore} from '../../utils/storage'
import { GoLogin, AddCart } from '../../request/api'
export default {
  name: 'Login',
  data() {
    let validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        user: '',
        pass: ''
      },
      rules: {
        user: [{ validator: validateUser, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }]
      },
      cart: []
    }
  },
  methods: {
    // 缓存未登录之前购物车里的数据
    login_addCart() {
      let cartArr = []
      let localCart = JSON.parse(getStore('buyCart'))
      if (localCart && localCart.length) {
        localCart.forEach(item => {
          cartArr.push({
            userId: getStore('id'),
            productId: item.productId,
            productNum: item.productNum
          })
        })
      }
      this.cart = cartArr
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 获取用户名和密码
          GoLogin(this.ruleForm).then(res => {
            if (res.data.code == 200) {
              let {username, token, id} = res.data
              // 持久化存储数据
              setStore('token', token)
              setStore('id', id)
              // 调用缓存的数据
              this.login_addCart()
              // 合并未登录以前购物车的数据
              if (this.cart && this.cart.length) {
                this.cart.forEach(item => {
                  AddCart(item).then(res => {
                    if (res.data.success == true) {
                      //......
                    }
                    removeStore('buyCart')
                    this.$router.back()
                  })
                })
              } else {
                this.$router.back()
              }
            }
          })
          // const res = await this.$http.post('/api/login', this.ruleForm)
          // console.log(res)
          // if (res.data.code == 200) {
          //   let {username, token, id} = res.data
          //   // 持久化存储数据
          //   setStore('token', token)
          //   setStore('id', id)
          //   // 调用缓存的数据
          //   this.login_addCart()
          //   // 合并未登录以前购物车的数据
          //   if (this.cart && this.cart.length) {
          //     console.log('cart',this.cart)
          //     this.cart.forEach(async item => {
          //       let res = await this.$http.post('/api/addCart', item)
          //       if (res.data.success == true) {
          //         //......
          //       }
          //       removeStore('buyCart')
          //       this.$router.back()
          //     })
          //   } else {
          //     this.$router.back()
          //   }
          // }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  }
}
</script>

<style  scoped>
.box {
  width: 450px;
  height: 350px;
  background: #fff;
  border: 1px solid #dadada;
  border-radius: 10px;
  position: absolute;
  top: 200px;
  left: 50%;
  transform: translateX(-50%);
  padding: 50px 50px 50px 10px;
  box-shadow: 0 9px 30px -6px rgba(0, 0, 0, 0.2),
    0 18px 20px -10px rgba(0, 0, 0, 0.04),
    0 18px 20px -10px rgba(0, 0, 0, 0.04),
    0 10px 20px -10px rgba(0, 0, 0, 0.04);
  text-align: center;
}
form {
  margin-top: 30px;
}
span {
  color: #333;
  font-weight: 400;
}
.login {
  width: 100%;
  height: 100%;
  overflow: visible;
  position: relative;
  background: url('/static/images/bg_9b9dcb65ff.png') repeat;
  background-size: 100px;
  min-height: 800px;
  min-width: 630px;
}
.icon {
  margin: 0 auto;
  width: 50px;
  height: 50px;
}
.icon img {
  display: block;
  width: 100%;
  height: 100%;
}
</style>